<template>
  <div class="records-page">
    <!-- 空状态 -->
    <div v-if="store.restRecords.length === 0" class="empty-state">
      <div class="empty-icon">📋</div>
      <h3>暂无休息记录</h3>
      <p>在日历中点击日期来添加休息记录</p>
    </div>
    
    <!-- 记录列表 -->
    <div v-else class="records-list">
      <!-- 进行中的休息 -->
      <div v-if="ongoingRecord" class="section ongoing-section">
        <div class="section-header">
          <span class="section-title">进行中</span>
          <van-tag type="warning" size="small">休息中</van-tag>
        </div>
        <div class="record-card ongoing">
          <div class="record-main">
            <div class="record-dates">
              <span class="date-value">{{ ongoingRecord.startDate }}</span>
              <span class="date-separator">→</span>
              <span class="date-value ongoing-text">进行中...</span>
            </div>
            <div class="record-duration">
              已休息 <strong>{{ getRestDays(ongoingRecord.startDate) }}</strong> 天
            </div>
            <div v-if="ongoingRecord.description" class="record-desc">
              {{ ongoingRecord.description }}
            </div>
          </div>
          <div class="record-actions">
            <van-button 
              size="small" 
              type="warning" 
              plain 
              round
              @click="endRest(ongoingRecord)"
            >
              结束休息
            </van-button>
            <van-button 
              size="small" 
              plain 
              round
              @click="editRecord(ongoingRecord)"
            >
              编辑
            </van-button>
          </div>
        </div>
      </div>
      
      <!-- 已完成的休息 -->
      <div v-if="completedRecords.length > 0" class="section completed-section">
        <div class="section-header">
          <span class="section-title">历史记录</span>
          <span class="section-count">{{ completedRecords.length }} 条</span>
        </div>
        
        <van-swipe-cell 
          v-for="record in completedRecords" 
          :key="record.id"
          class="record-swipe"
        >
          <div class="record-card" @click="showRecordDetail(record)">
            <div class="record-main">
              <div class="record-dates">
                <span class="date-value">{{ record.startDate }}</span>
                <span class="date-separator">→</span>
                <span class="date-value">{{ record.endDate }}</span>
              </div>
              <div class="record-duration">
                休息 <strong>{{ calculateDays(record.startDate, record.endDate) }}</strong> 天
              </div>
              <div v-if="record.description" class="record-desc">
                {{ record.description }}
              </div>
            </div>
            <van-icon name="arrow" class="record-arrow" />
          </div>
          
          <template #right>
            <van-button 
              square 
              type="primary" 
              text="编辑"
              class="swipe-btn edit-btn"
              @click="editRecord(record)"
            />
            <van-button 
              square 
              type="danger" 
              text="删除"
              class="swipe-btn delete-btn"
              @click="deleteRecord(record)"
            />
          </template>
        </van-swipe-cell>
      </div>
      
      <!-- 统计摘要 -->
      <div class="summary-card">
        <div class="summary-item">
          <span class="summary-label">总休息次数</span>
          <span class="summary-value">{{ store.restRecords.length }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">总休息天数</span>
          <span class="summary-value">{{ totalRestDays }}</span>
        </div>
      </div>
    </div>
    
    <!-- 记录详情弹窗 -->
    <van-popup
      v-model:show="showDetail"
      position="bottom"
      round
      class="detail-popup"
    >
      <div class="detail-content" v-if="selectedRecord">
        <h3>休息记录详情</h3>
        
        <div class="detail-info">
          <div class="info-row">
            <span class="info-label">开始日期</span>
            <span class="info-value">{{ selectedRecord.startDate }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">结束日期</span>
            <span class="info-value">{{ selectedRecord.endDate || '进行中' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">休息天数</span>
            <span class="info-value highlight">
              {{ selectedRecord.endDate 
                ? calculateDays(selectedRecord.startDate, selectedRecord.endDate) 
                : getRestDays(selectedRecord.startDate) }} 天
            </span>
          </div>
          <div v-if="selectedRecord.description" class="info-row desc">
            <span class="info-label">备注</span>
            <span class="info-value">{{ selectedRecord.description }}</span>
          </div>
        </div>
        
        <div class="detail-actions">
          <van-button block round type="primary" @click="editRecord(selectedRecord)">
            编辑记录
          </van-button>
          <van-button block round plain type="danger" @click="deleteRecord(selectedRecord)">
            删除记录
          </van-button>
        </div>
      </div>
    </van-popup>
    
    <!-- 编辑弹窗 -->
    <van-popup
      v-model:show="showEdit"
      position="bottom"
      round
      closeable
      class="edit-popup"
    >
      <div class="edit-content">
        <h3>{{ editingRecord?.id ? '编辑休息记录' : '添加休息记录' }}</h3>
        
        <van-cell-group inset class="edit-form">
          <van-cell 
            title="开始日期" 
            :value="editForm.startDate || '请选择'"
            is-link
            @click="openDatePicker('start')"
          />
          <van-cell 
            title="结束日期" 
            :value="editForm.endDate || '进行中'"
            is-link
            @click="openDatePicker('end')"
          />
          <van-field
            v-model="editForm.description"
            label="备注"
            placeholder="可选，添加备注"
            maxlength="200"
          />
        </van-cell-group>
        
        <div class="edit-actions">
          <van-button block round type="primary" @click="saveRecord" :loading="saving">
            保存
          </van-button>
        </div>
      </div>
    </van-popup>
    
    <!-- 结束休息弹窗 -->
    <van-popup
      v-model:show="showEndRest"
      position="bottom"
      round
      closeable
      class="end-rest-popup"
    >
      <div class="end-rest-content">
        <h3>结束休息</h3>
        <p class="end-rest-info">
          休息开始于 <strong>{{ endRestRecord?.startDate }}</strong>
        </p>
        
        <van-cell-group inset class="edit-form">
          <van-cell 
            title="结束日期" 
            :value="endRestDate || '请选择'"
            is-link
            @click="openEndDatePicker"
          />
        </van-cell-group>
        
        <div class="edit-actions">
          <van-button block round type="warning" @click="confirmEndRest" :loading="saving">
            确认结束
          </van-button>
        </div>
      </div>
    </van-popup>
    
    <!-- 日期选择器 -->
    <van-popup
      v-model:show="showDatePicker"
      position="bottom"
      round
      class="date-picker-popup"
    >
      <van-date-picker
        v-model="datePickerValue"
        :title="datePickerTitle"
        :min-date="datePickerMinDate"
        :max-date="datePickerMaxDate"
        @confirm="handleDatePickerConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { useAppStore } from '../stores/index.js'

const store = useAppStore()

// 弹窗状态
const showDetail = ref(false)
const showEdit = ref(false)
const showEndRest = ref(false)
const showDatePicker = ref(false)

// 选中的记录
const selectedRecord = ref(null)
const editingRecord = ref(null)
const endRestRecord = ref(null)

// 编辑表单
const editForm = ref({
  startDate: '',
  endDate: '',
  description: ''
})

// 结束休息日期
const endRestDate = ref('')

// 保存状态
const saving = ref(false)

// 日期选择器
const datePickerType = ref('start')
const datePickerValue = ref([])
const datePickerTitle = computed(() => 
  datePickerType.value === 'start' ? '选择开始日期' : '选择结束日期'
)
const datePickerMinDate = computed(() => {
  if (datePickerType.value === 'end') {
    if (showEndRest.value && endRestRecord.value) {
      return new Date(endRestRecord.value.startDate)
    }
    if (editForm.value.startDate) {
      return new Date(editForm.value.startDate)
    }
  }
  return new Date(2020, 0, 1)
})
const datePickerMaxDate = computed(() => new Date())

// 计算属性
const ongoingRecord = computed(() => 
  store.restRecords.find(r => !r.endDate)
)

const completedRecords = computed(() => 
  store.restRecords
    .filter(r => r.endDate)
    .sort((a, b) => new Date(b.startDate) - new Date(a.startDate))
)

const totalRestDays = computed(() => {
  return store.restRecords.reduce((total, record) => {
    if (record.endDate) {
      return total + calculateDays(record.startDate, record.endDate)
    } else {
      return total + getRestDays(record.startDate)
    }
  }, 0)
})

// 计算天数
const calculateDays = (start, end) => {
  const startDate = new Date(start)
  const endDate = new Date(end)
  const diffTime = endDate - startDate
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
  return Math.max(1, diffDays)
}

const getRestDays = (startDate) => {
  const start = new Date(startDate)
  const today = new Date()
  const diffTime = today - start
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return Math.max(1, diffDays)
}

// 显示记录详情
const showRecordDetail = (record) => {
  selectedRecord.value = record
  showDetail.value = true
}

// 编辑记录
const editRecord = (record) => {
  editingRecord.value = record
  editForm.value = {
    startDate: record.startDate,
    endDate: record.endDate || '',
    description: record.description || ''
  }
  showDetail.value = false
  showEdit.value = true
}

// 删除记录
const deleteRecord = async (record) => {
  try {
    await showConfirmDialog({
      title: '删除确认',
      message: '确定要删除这条休息记录吗？'
    })
    
    await store.deleteRestRecord(record.id)
    showDetail.value = false
    showToast({
      message: '删除成功',
      icon: 'success'
    })
    
    // 刷新统计
    await store.getStatistics({ includeTravel: store.includeTravel })
  } catch (error) {
    if (error !== 'cancel' && error.message !== 'cancel') {
      showToast({
        message: error.message || '删除失败',
        icon: 'fail'
      })
    }
  }
}

// 结束休息
const endRest = (record) => {
  endRestRecord.value = record
  endRestDate.value = getTodayStr()
  showEndRest.value = true
}

// 打开日期选择器
const openDatePicker = (type) => {
  datePickerType.value = type
  const currentDate = type === 'start' ? editForm.value.startDate : editForm.value.endDate
  
  if (currentDate) {
    datePickerValue.value = currentDate.split('-')
  } else {
    const today = new Date()
    datePickerValue.value = [
      today.getFullYear().toString(),
      (today.getMonth() + 1).toString().padStart(2, '0'),
      today.getDate().toString().padStart(2, '0')
    ]
  }
  
  showDatePicker.value = true
}

// 打开结束日期选择器
const openEndDatePicker = () => {
  datePickerType.value = 'end'
  
  if (endRestDate.value) {
    datePickerValue.value = endRestDate.value.split('-')
  } else {
    const today = new Date()
    datePickerValue.value = [
      today.getFullYear().toString(),
      (today.getMonth() + 1).toString().padStart(2, '0'),
      today.getDate().toString().padStart(2, '0')
    ]
  }
  
  showDatePicker.value = true
}

// 处理日期选择确认
const handleDatePickerConfirm = ({ selectedValues }) => {
  const dateStr = selectedValues.join('-')
  
  if (showEndRest.value) {
    endRestDate.value = dateStr
  } else if (datePickerType.value === 'start') {
    editForm.value.startDate = dateStr
  } else {
    editForm.value.endDate = dateStr
  }
  
  showDatePicker.value = false
}

// 保存记录
const saveRecord = async () => {
  if (!editForm.value.startDate) {
    showToast('请选择开始日期')
    return
  }
  
  saving.value = true
  
  try {
    const record = {
      startDate: editForm.value.startDate,
      endDate: editForm.value.endDate || null,
      description: editForm.value.description || ''
    }
    
    if (editingRecord.value?.id) {
      await store.updateRestRecord(editingRecord.value.id, record)
      showToast({ message: '更新成功', icon: 'success' })
    } else {
      await store.addRestRecord(record)
      showToast({ message: '添加成功', icon: 'success' })
    }
    
    showEdit.value = false
    await store.getStatistics({ includeTravel: store.includeTravel })
  } catch (error) {
    showToast({
      message: error.message || '保存失败',
      icon: 'fail'
    })
  } finally {
    saving.value = false
  }
}

// 确认结束休息
const confirmEndRest = async () => {
  if (!endRestDate.value) {
    showToast('请选择结束日期')
    return
  }
  
  saving.value = true
  
  try {
    await store.updateRestRecord(endRestRecord.value.id, {
      ...endRestRecord.value,
      endDate: endRestDate.value
    })
    
    showEndRest.value = false
    showToast({
      message: '休息已结束',
      icon: 'success'
    })
    
    await store.getStatistics({ includeTravel: store.includeTravel })
  } catch (error) {
    showToast({
      message: error.message || '操作失败',
      icon: 'fail'
    })
  } finally {
    saving.value = false
  }
}

// 获取今天日期字符串
const getTodayStr = () => {
  const today = new Date()
  return today.getFullYear() + '-' + 
         (today.getMonth() + 1).toString().padStart(2, '0') + '-' + 
         today.getDate().toString().padStart(2, '0')
}
</script>

<style scoped>
.records-page {
  padding: 16px;
  padding-bottom: 80px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state h3 {
  color: var(--text-primary);
  margin-bottom: 8px;
}

.empty-state p {
  color: var(--text-muted);
  font-size: 14px;
}

/* 记录列表 */
.records-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 区块 */
.section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 4px;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
}

.section-count {
  font-size: 13px;
  color: var(--text-muted);
}

/* 记录卡片 */
.record-card {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.record-card.ongoing {
  border: 1px solid var(--warning-color);
  background: rgba(245, 158, 11, 0.1);
  flex-direction: column;
  align-items: stretch;
}

.record-main {
  flex: 1;
}

.record-dates {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.date-value {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
}

.date-separator {
  color: var(--text-muted);
}

.ongoing-text {
  color: var(--warning-color);
}

.record-duration {
  font-size: 13px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.record-duration strong {
  color: var(--accent-primary);
}

.record-desc {
  font-size: 12px;
  color: var(--text-muted);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.record-arrow {
  color: var(--text-muted);
  font-size: 16px;
}

.record-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

/* 滑动单元格 */
.record-swipe {
  margin-bottom: 8px;
}

.swipe-btn {
  height: 100%;
}

.edit-btn {
  background: var(--accent-primary) !important;
}

/* 统计摘要 */
.summary-card {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 16px;
  display: flex;
  justify-content: space-around;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.summary-label {
  font-size: 12px;
  color: var(--text-muted);
}

.summary-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--accent-primary);
}

/* 详情弹窗 */
.detail-popup {
  background: var(--card-bg) !important;
}

.detail-content {
  padding: 24px;
}

.detail-content h3 {
  text-align: center;
  color: var(--text-primary);
  margin-bottom: 24px;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-row.desc {
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.info-label {
  font-size: 14px;
  color: var(--text-muted);
}

.info-value {
  font-size: 15px;
  color: var(--text-primary);
  font-weight: 500;
}

.info-value.highlight {
  color: var(--accent-primary);
  font-weight: 700;
}

.detail-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 编辑弹窗 */
.edit-popup, .end-rest-popup {
  background: var(--card-bg) !important;
  max-height: 80vh;
}

.edit-content, .end-rest-content {
  padding: 24px;
}

.edit-content h3, .end-rest-content h3 {
  text-align: center;
  color: var(--text-primary);
  margin-bottom: 20px;
}

.end-rest-info {
  text-align: center;
  color: var(--text-secondary);
  margin-bottom: 20px;
}

.end-rest-info strong {
  color: var(--accent-primary);
}

.edit-form {
  background: transparent !important;
  margin-bottom: 20px;
}

.edit-form :deep(.van-cell) {
  background: var(--card-bg-hover) !important;
  margin-bottom: 8px;
  border-radius: 8px;
}

.edit-form :deep(.van-cell__title) {
  color: var(--text-secondary);
}

.edit-form :deep(.van-cell__value) {
  color: var(--text-primary);
}

.edit-actions {
  padding-top: 10px;
}

/* 日期选择器弹窗 */
.date-picker-popup {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker) {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker__toolbar) {
  background: var(--card-bg);
}

.date-picker-popup :deep(.van-picker__title) {
  color: var(--text-primary);
}

.date-picker-popup :deep(.van-picker__confirm) {
  color: var(--accent-primary);
}

.date-picker-popup :deep(.van-picker__cancel) {
  color: var(--text-muted);
}

.date-picker-popup :deep(.van-picker-column__item) {
  color: var(--text-secondary);
}

.date-picker-popup :deep(.van-picker-column__item--selected) {
  color: var(--text-primary);
}
</style>

